//
// Created by HP on 2025/12/1.
//

#include "Friend.h"
#include <iostream>

Friend::Friend() : Model("friends") {
    this->status = "pending"; // 默认状态为待接受
    setTableDefault("user1_id", "VARCHAR(50) NOT NULL");
    setTableDefault("user2_id", "VARCHAR(50) NOT NULL");
    setTableDefault("status", "VARCHAR(20) NOT NULL DEFAULT 'pending'");
    setTableDefault("create_time", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
    setTableDefault("update_time", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
    
    // 可以考虑添加一个复合唯一索引，避免重复的好友关系
    // 例如：ALTER TABLE friends ADD UNIQUE KEY unique_friendship (user1_id, user2_id);
}

void Friend::bind(const std::string& key, const std::string& value) {
    if (!TableCols.count(key)) {
        std::cerr << "Error: Invalid key for friend bind" << std::endl;
        return;
    }
    
    std::string selectSql = "SELECT * FROM " + TableName + " WHERE " + key + " = '" + Model::escapeSqlLiteral(value) + "';";
    std::vector<std::map<std::string, std::string>> result = DBConnector::getInstance()->query(selectSql);

    if (result.empty()) {
        std::cerr << "bind failed: SQL execution error or no result. SQL: " << selectSql << std::endl;
        return;
    }

    std::cout << "bind success. Table: " << TableName << std::endl;

    // 好友记录可能有多条，这里取第一条
    if (result.size() > 1) {
        std::cout << "Warning: Multiple friend records found with the same " << key << ", using the first one." << std::endl;
    }
    
    this->id = result[0]["id"];
    this->user1_id = result[0]["user1_id"];
    this->user2_id = result[0]["user2_id"];
    this->status = result[0]["status"];
    this->create_time = result[0]["create_time"];
    this->update_time = result[0]["update_time"];
    this->isBind = true;
}

bool Friend::save() {
    std::string insertSql = "INSERT INTO " + TableName + " (user1_id, user2_id, status) VALUES ('" 
                          + Model::escapeSqlLiteral(user1_id) + "', '" 
                          + Model::escapeSqlLiteral(user2_id) + "', '" 
                          + Model::escapeSqlLiteral(status) + "');";
    
    int executeCode = DBConnector::getInstance()->execute(insertSql);
    if (executeCode == -1) {
        std::cerr << "save friend failed: SQL execution error. SQL: " << insertSql << std::endl;
        std::cerr << "Database error: " << DBConnector::getInstance()->getError() << std::endl;
        return false;
    } else {
        std::cout << "save friend success. Table: " << TableName << std::endl;
        return true;
    }
}
